<template>
  <div class="products-view">
    <div class="page-header">
      <h1>商品管理</h1>
      <p>管理您的商品信息、库存和价格</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称/SKU">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入商品名称或SKU"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>

        <el-form-item label="商品分类">
          <el-tree-select
            v-model="searchForm.category_id"
            :data="categoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择分类"
            clearable
            check-strictly
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="商品状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="上架" value="active" />
            <el-option label="下架" value="inactive" />
            <el-option label="草稿" value="draft" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>商品列表 ({{ pagination.total }})</span>
          <div class="header-actions">
            <el-button type="primary" :icon="Plus" @click="handleAdd">
              添加商品
            </el-button>
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="selectedProducts.length === 0"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="productList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column label="商品信息" min-width="300">
          <template #default="{ row }">
            <div class="product-info">
              <el-image
                :src="row.main_image_url"
                class="product-image"
                fit="cover"
                :preview-src-list="[row.main_image_url]"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-details">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-sku">SKU: {{ row.sku }}</div>
                <div class="product-category">{{ row.category_name || '未分类' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="价格" width="120" align="center">
          <template #default="{ row }">
            <div class="price-info">
              <div class="sale-price">¥{{ row.price }}</div>
              <div v-if="row.market_price" class="market-price">
                ¥{{ row.market_price }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="stock_quantity" label="库存" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.stock_quantity <= 5 ? 'danger' : row.stock_quantity <= 20 ? 'warning' : 'success'"
            >
              {{ row.stock_quantity }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="sales_count" label="销量" width="100" align="center" />

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'active' ? 'success' : row.status === 'inactive' ? 'danger' : 'info'"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="240" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                :type="row.status === 'active' ? 'warning' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 'active' ? '下架' : '上架' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Delete, Edit, Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 路由
const router = useRouter()

// 状态管理
const loading = ref(false)
const productList = ref<any[]>([])
const selectedProducts = ref<any[]>([])
const categoryOptions = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  category_id: null,
  status: null
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 方法
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '上架',
    inactive: '下架',
    draft: '草稿'
  }
  return statusMap[status] || status
}

const loadCategories = async () => {
  try {
    const response = await request.get('/categories/tree')
    categoryOptions.value = response.data
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadProducts = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      search: searchForm.search,
      category_id: searchForm.category_id,
      status: searchForm.status
    }

    const response = await request.get('/products', { params })
    productList.value = response.data.products || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadProducts()
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.category_id = null
  searchForm.status = null
  pagination.page = 1
  loadProducts()
}

const handleAdd = () => {
  router.push('/products/create')
}

const handleEdit = (row: any) => {
  router.push(`/products/edit/${row.id}`)
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${row.name}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await request.delete(`/products/${row.id}`)
    ElMessage.success('删除成功')
    await loadProducts()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const handleToggleStatus = async (row: any) => {
  try {
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    const action = newStatus === 'active' ? '上架' : '下架'

    await request.put(`/products/${row.id}`, { status: newStatus })
    ElMessage.success(`${action}成功`)
    await loadProducts()
  } catch (error: any) {
    console.error('更新商品状态失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedProducts.value.length} 个商品吗？删除后不可恢复！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedProducts.value.map(item => item.id)
    await request.delete('/products/batch', { data: { ids } })
    ElMessage.success('批量删除成功')
    selectedProducts.value = []
    await loadProducts()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error(error.response?.data?.message || '批量删除失败')
    }
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadProducts()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadProducts()
}

// 生命周期
onMounted(() => {
  loadCategories()
  loadProducts()
})
</script>

<style scoped>
.products-view {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.filter-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.content-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-sku {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.product-category {
  font-size: 12px;
  color: #606266;
}

.price-info {
  text-align: center;
}

.sale-price {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

.market-price {
  font-size: 12px;
  color: #909399;
  text-decoration: line-through;
  margin-top: 2px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .products-view {
    margin: 0 16px;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .product-image {
    width: 50px;
    height: 50px;
  }
}
</style>
